<template>
    <div>
        <Category />
        <el-card :style="{ marginTop: '30px' }" shadow="always" :body-style="{ padding: '20px' }">
            <SkuForm v-if='showState === 0' :spuForm="spuForm" @setState='setState' />
            <SpuForm v-if='showState === 1' :spuForm="spuForm" @setState='setState' />
            <SpuList v-if='showState === 2' @setState='setState' />
        </el-card>

    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Spu",
});
</script>

<script setup lang="ts">
import { ref } from 'vue'
import SkuForm from './components/SkuForm/index.vue'
import SpuForm from './components/SpuForm/index.vue'
import SpuList from './components/SpuList/index.vue'
import useAttrStore from '@/stores/attr'
import { storeToRefs } from 'pinia'
import type { SpuInfoType } from '@/api/spu'


//拿到pinia中的三级分类数据
const attrStore = useAttrStore()
const { category3Id } = storeToRefs(attrStore)

//声明一个数据,控制视图中的哪一个组件渲染
const showState = ref(2)

//保存完整的spuInfo数据,如果是新增,则把初始值传递给SpuForm组件,如果是编辑,则初始数据替换,然后传递给SpuForm组件
const spuForm = ref<SpuInfoType>({
    category3Id: category3Id.value,
    description: '',
    tmId: null,
    spuName: '',
    spuImageList: [],
    spuSaleAttrList: [],
})
//封装一个自定义事件的回调函数,接收子组件传值,控制组件展示
const setState = (state: number, row?: SpuInfoType) => {
    showState.value = state
    if (row) {
        //把编辑传递的Spu数据保存在初始值上
        spuForm.value = row
    } else {
        //当用户点击的是新增过来的时候,spuInfo可能残留之前编辑传递过来的数据,所以我们要再次初始化数据
        spuForm.value = {
            category3Id: category3Id.value,
            description: '',
            tmId: null,
            spuName: '',
            spuImageList: [],
            spuSaleAttrList: [],
        }
    }
}
</script>